def jsonString(txt):
    result = "{"
    result += '"msg": "' + str(txt) + '"'
    result += "}"
    return result

def jsonDict(myDict):
    result = "{"
    for k in myDict:
        result += '"' + str(k) + '": "' + str(myDict[k]) + '", '
    result = result[:len(result)-2]
    result += "}"
    return result

def jsonListOfDicts(list):
    result = "{"
    result = "'result':"
    for dict in list:
        result += jsonDict(dict.as_dict()) + ','
    result = result[:len(result)-1]
    result += "}"
    return result


def jsonDictOfDicts(myDict):
    result = "{"
    for k in myDict:
        result += '"' + k + '":  '
        if type(myDict[k]) is dict:
            result += jsonDict(myDict[k]) + ', '
        else:
            result += '"' + myDict[k] + '", '
    
    result = result[:len(result) - 2]
    result += "}"
    return result


def queryXInArea(lat, lng, delta, username='', placename=''):
    ''' searches given area for all/filtered people/places''' 
    checkinsList=[]
    usersList = []
#    delta = 0.1
    if lat:    
        Llat = lat - delta; Rlat = lat + delta
        Dlng = lng - delta; Ulng = lng + delta
        
        #the query that get all places in the given area 
        query = (db.places.lat <= Rlat) & (db.places.lat >= Llat) &\
            (db.places.long <= Ulng) & (db.places.long >= Dlng)
        
        # to filter places
        if placename:
          query = query & (db.places.name == placename)
  
        placesList = db(query).select()
        
        #get all people in the given area
        for place in placesList:
            for checkinId in place.checkins:
                checkinsList.append(db(db.checkins.id == checkinId).select())
                
        for checkin in checkinsList:
            usersList.append(db(db.users.id == checkin.user).select())
        
        #to filter people
        if username:
            for user in usersList:
                if not user.first_name == username or not user.last_name == username:
                    usersList.remove(user) 
        
    else: 
        usersList = False
    
    return dict(usersList=usersList, placesList=placesList)


#def getBorders(lat, lng, shift):
#    if lat:    
#        borders = dict(Llat = lat - shift, Rlat = lat + shift,\
#        Dlng = lng - shift, Ulng = lng + shift)
#    borders = False
#    return borders
